package com.firefighting.controller;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.firefighting.entity.BuildingFunction;
import com.firefighting.entity.Contract;
import com.firefighting.entity.Enterprise;
import com.firefighting.entity.FirstMaintenanceProject;
import com.firefighting.entity.User;
import com.firefighting.entity.UserBasicInfo;
import com.firefighting.service.BuildingFunctionService;
import com.firefighting.service.BuildingService;
import com.firefighting.service.ContractService;
import com.firefighting.service.EnterpriseService;
import com.firefighting.service.MaintenancePlanService;
import com.firefighting.service.MaintenanceService;
import com.firefighting.service.ProprietorService;
import com.firefighting.service.UserBasicInfoService;

@Controller
@RequestMapping("contract")
public class ContractController
{
	@Autowired
	private ContractService contractService;
	@Autowired
	private UserBasicInfoService userBasicInfoService;
	@Autowired
	private MaintenanceService maintenanceService;
	@Autowired
	private ProprietorService proprietorService;
	@Autowired
	private EnterpriseService enterpriseService;
	@Autowired
	private BuildingService buildingService;
	@Autowired
	private BuildingFunctionService buildingFunctionService;
	@Autowired
	private MaintenancePlanService maintenancePlanService;

	/**
	 * @function 根据合同id查询合同内容
	 * @author zhyan
	 * @date 2018.6.7 9:34
	 * @return
	 * 三个列表：业主、项目负责人、建筑物
	 * @author Liuxc 修改、维护
	 * @author zhyan 修改维护
	 * @throws Exception 
	 */
	@RequestMapping("getContractInfo")
	private String getContractInfo(HttpServletRequest request, Model model) throws Exception
	{
		int id = Integer.parseInt(request.getParameter("Id"));//合同ID
		//业主全集
		@SuppressWarnings("rawtypes")
		List<HashMap> proprietors = proprietorService.queryAllProprietor();
		model.addAttribute("proprietor", proprietors);
		
		//项目负责人全集
		@SuppressWarnings("rawtypes")
		List<HashMap> projectManager = userBasicInfoService.queryProjectManagerList();
		model.addAttribute("projectLeaderList", projectManager);
		
		//建筑物列表
		@SuppressWarnings("rawtypes")
		List<HashMap> buildings = buildingService.queryAllBuilding();
		model.addAttribute("building", buildings);
		
		//建筑物使用功能
		List<BuildingFunction> function = buildingFunctionService.queryAllFunction();
		model.addAttribute("function", function);
		
		if(id == -1)
		{//
			return "contract/addContract";
		}
		
		//根据合同id查询合同信息
		Contract contract = contractService.queryContract(id);//维保企业和合同对应,对应负责人放到这里
		@SuppressWarnings("rawtypes")
		HashMap hashMap = contractService.queryContractHash(id);
		System.out.println(hashMap);
		model.addAttribute("content1", hashMap);
		
		//合同对应的维保企业
		Enterprise enterprise = enterpriseService.getEneterpriseById(contract.getMaintenanceEnterpriseId());
		model.addAttribute("enterprise", enterprise);
		
		return "contract/editContract";
		
	}
	@RequestMapping("getContractInfoZD")
	//查看合同信息
	private String getContractInfoZD(HttpServletRequest request, Model model) throws Exception
	{
		int id = Integer.parseInt(request.getParameter("Id"));//合同ID
		/*//业主全集
		@SuppressWarnings("rawtypes")
		List<HashMap> proprietors = proprietorService.queryAllProprietor();
		model.addAttribute("proprietor", proprietors);
		
		//项目负责人全集
		@SuppressWarnings("rawtypes")
		List<HashMap> projectManager = userBasicInfoService.queryProjectManagerList();
		model.addAttribute("projectLeaderList", projectManager);
		
		//建筑物列表
		@SuppressWarnings("rawtypes")
		List<HashMap> buildings = buildingService.queryAllBuilding();
		model.addAttribute("building", buildings);
		
		//建筑物使用功能
		List<BuildingFunction> function = buildingFunctionService.queryAllFunction();
		model.addAttribute("function", function);
		
		if(id == -1)
		{//
			return "contract/addContract";
		}*/
		
		//根据合同id查询合同信息
		Contract contract = contractService.queryContract(id);//维保企业和合同对应,对应负责人放到这里
		@SuppressWarnings("rawtypes")
		HashMap hashMap = contractService.queryContractHash(id);
		System.out.println(hashMap);
		model.addAttribute("content1", hashMap);
		
		/*//合同对应的维保企业
		Enterprise enterprise = enterpriseService.getEneterpriseById(contract.getMaintenanceEnterpriseId());
		model.addAttribute("enterprise", enterprise);
		*/
		
		return "maintenanceProject/viewContract";
	}
	
	/**
	 * @author zhyan
	 * @function 查询所有合同对应的业主名称、负责人名称和企业名称
	 * @date 2018.6.12
	 * @throws JsonGenerationException
	 * @throws JsonMappingException
	 * @throws IOException
	 */
	@RequestMapping("getAllPEPMByContract")
	public String getAllPEPMByContract(HttpServletRequest request, Model model) throws JsonGenerationException, JsonMappingException, IOException
	{
		List<Integer> idList = contractService.queryAllContractIds();
		ObjectMapper objectMapper = new ObjectMapper();
		
		if(idList.size() > 0)
		{
			@SuppressWarnings("rawtypes")
			List<HashMap> pepmInfo = contractService.queryPEPMByContractIdList(idList);
			model.addAttribute("content", objectMapper.writeValueAsString(pepmInfo));
		}
		else
		{
			model.addAttribute("content", objectMapper.writeValueAsString(null));
		}
		
		return "contract/editContract";
	}
	
	/**
	 * @author Liuxc
	 * @function 根据角色查询合同列表
	 * @date 2018.6.9
	 * @return contract/contraclList
	 * @throws IOException 
	 * @throws JsonMappingException 
	 * @throws JsonGenerationException 
	 */
	@RequestMapping("showContract")
	private String showContract(HttpServletRequest request,HttpServletResponse response, Model model) throws JsonGenerationException, JsonMappingException, IOException
	{
		
		HttpSession session = request.getSession();
		User currentUser = (User) session.getAttribute("currentUser");
		UserBasicInfo userBasicInfo = userBasicInfoService.getInfoByAccount(currentUser.getUsername());
		int roleId = currentUser.getRoleid();
		//List<HashMap<String, Object>> contractList = new ArrayList<HashMap<String,Object>>();
		ObjectMapper objectMapper = new ObjectMapper();
		if(roleId == 11)
		{//如果是平台管理员，返回所有合同
			//contractList = contractService.queryAllContract();
			//List<Integer> enterIDList = enterpriseService.queryAllEnterpriseIdList();
			
			@SuppressWarnings("rawtypes")
			List<HashMap> pepm = contractService.queryContractInfo();
			model.addAttribute("content", objectMapper.writeValueAsString(pepm));
		}
		else if(roleId == 9)
		{//如果是消防总队，返回该省所属企业的所有合同
			//List<Integer> enterIdList = enterService.getEnterpriseByProvence(userBasicInfo.getProvince());
			//contractList = contractService.getContractByEnterpriseIdList(enterIdList);
			System.out.println("zongdui");
			@SuppressWarnings("rawtypes")
			List<HashMap> pepm = contractService.queryContractInfoByProvince(userBasicInfo.getProvince());
			model.addAttribute("content", objectMapper.writeValueAsString(pepm));
			System.out.println(pepm);
			return "maintenanceProject/zdMaintenanceProject";
		}
		else if(roleId == 10)
		{//如果是消防支队，返回该市所属企业的所有合同
			
			//List<Integer> enterIdList = enterService.getEnterpriseByCity(userBasicInfo.getCity());
			//contractList = contractService.getContractByEnterpriseIdList(enterIdList);
			
			@SuppressWarnings("rawtypes")
			List<HashMap> pepm = contractService.queryContractInfoByProvinceAndCity(userBasicInfo.getProvince(), userBasicInfo.getCity());
			model.addAttribute("content", objectMapper.writeValueAsString(pepm));
			
		}
		else if(roleId == 2)
		{
			//项目负责人，返回所属企业的所有合同
			//contractList = contractService.getContractByEnterpriseId(userBasicInfo.getEnterpriseId());
			//System.out.println(contractList);
			//List<Proprietor> proprietorList = new ArrayList<Proprietor>();
			//proprietorList  = proprietorService.getProprietorByEnterprise(userBasicInfo.getEnterpriseId());
			//session.setAttribute("proprietorList", proprietorList);
			//List<Integer> enterIdList = new ArrayList<Integer>();
			//enterIdList.add(userBasicInfo.getEnterpriseId());
			
			@SuppressWarnings("rawtypes")
			List<HashMap> pepm = contractService.queryContractInfoByProjectLeaderAccount(userBasicInfo.getLoginId());
			model.addAttribute("content", objectMapper.writeValueAsString(pepm));
		}
		else if(roleId == 1)
		{
			//如果是企业管理员,返回该企业所有项目负责人的合同
			//List<String> usernameList = userBasicInfoService.queryPMByEnterpriseId(userBasicInfo.getEnterpriseId());
			@SuppressWarnings("rawtypes")
			List<HashMap> pepm = contractService.queryAllContractInfoWithEnterprise(userBasicInfo.getEnterpriseId()/*usernameList*/);
			model.addAttribute("content", objectMapper.writeValueAsString(pepm));
		}
		//model.addAttribute("contractList", objectMapper.writeValueAsString(contractList));
		
		return "contract/contractView";
	}
	
	/**
	 * @author zhyan
	 * @function 添加合同
	 * @date 2018.6.7
	 * @throws ParseException 
	 * @throws IOException 
	 * @throws JsonMappingException 
	 * @throws JsonGenerationException 
	 * 
	 * @author zhyan 修改
	 * @throws IllegalStateException 
	 * @date 2018.6.11
	 */
	@RequestMapping("addContract")
	private String addContract(MultipartFile file, HttpServletRequest request, Model model) throws ParseException, IllegalStateException, IOException
	{
		User user = (User) request.getSession().getAttribute("currentUser");
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		
		String projectName = request.getParameter("projectName");
		int proprietorId = Integer.parseInt(request.getParameter("proprietorId"));//业主名称，返回是业主id
		String province = request.getParameter("province");
		String city = request.getParameter("city");
		String district = request.getParameter("area");
		String address = request.getParameter("address");
		String cityPartner = request.getParameter("cityPartner");
		int maintenanceEnterpriseId = userBasicInfoService.getInfoByAccount(user.getUsername()).getEnterpriseId();
		//String proprietorProjectContact = request.getParameter("proprietorProjectContact");
		//String proprietorSceneContact = request.getParameter("proprietorSceneContact");
		String projectLeaderAccount= userBasicInfoService.getInfoById(Integer.parseInt(request.getParameter("projectCharge"))).getLoginId();//项目负责人，返回项目负责人的账号
		String singdate=request.getParameter("signDate");
		System.out.println("sign "+singdate);
		Date signDate = sdf.parse(singdate);
		Date endDate = sdf.parse(request.getParameter("endDate"));
		java.sql.Date sqlSignDate = new java.sql.Date(signDate.getTime());
		java.sql.Date sqlEndDate = new java.sql.Date(endDate.getTime());
		BigDecimal totalPrice = new BigDecimal(request.getParameter("totalPrice"));
		String buildingFunction = request.getParameter("buildingFunction");//返回建筑物使用功能
		String servicePhone = request.getParameter("sevicePhone");
		//String accessory = request.getParameter("accessory");
		String status = request.getParameter("status");
		String accessory = null;
		
		String path = request.getSession().getServletContext().getRealPath("upload");
		String fileName = file.getOriginalFilename();//获取文件名
		
		//只有存在上传文件时，才会执行下面的方法
		if(!fileName.equals(null) && !fileName.equals(""))
		{
			File dir = new File(path, fileName);
			
			if (!dir.exists())
			{
				dir.mkdirs();
			}
			// MultipartFile自带的解析方法
			file.transferTo(dir);
			accessory = dir.toString();
		}
		
		Contract contract = new Contract();
		contract.setProjectName(projectName);
		contract.setProprietorId(proprietorId);
		contract.setProvince(province);
		contract.setCity(city);
		contract.setDistrict(district);
		contract.setAddress(address);
		contract.setCityPartner(cityPartner);
		contract.setMaintenanceEnterpriseId(maintenanceEnterpriseId);
		//contract.setProprietorProjectContact(proprietorProjectContact);
		//contract.setProprietorSceneContact(proprietorSceneContact);
		contract.setProjectLeaderAccount(projectLeaderAccount);
		contract.setSignDate(sqlSignDate);
		contract.setEndDate(sqlEndDate);
		contract.setTotalPrice(totalPrice);
		contract.setBuildingFunction(buildingFunction);
		contract.setServicePhone(servicePhone);
		contract.setAccessory(accessory);
		contract.setStatus(status);
		
		int number = contractService.addContract(contract);
		if(number > 0)
		{
			model.addAttribute("message", "true");//添加成功
		}
		else
		{
			model.addAttribute("message", "false");//添加失败
		}
		
		return "redirect:/contract/showContract.htm";
	}
	
	/**
	 * @author zhyan
	 * @function 获取业主和企业名称的全集
	 * @date 2018.6.12
	 * @throws JsonGenerationException
	 * @throws JsonMappingException
	 * @throws IOException
	 */
	@RequestMapping("getProprietorAndProjectName")
	public String getProprietorAndProjectName(HttpServletRequest request, Model model) throws JsonGenerationException, JsonMappingException, IOException
	{
		//业主全集
		@SuppressWarnings("rawtypes")
		List<HashMap> proprietors = proprietorService.queryAllProprietor();
		model.addAttribute("allProprietor", proprietors);
		
		//项目负责人全集
		@SuppressWarnings("rawtypes")
		List<HashMap> projectManager = userBasicInfoService.queryProjectManagerList();
		model.addAttribute("manager", projectManager);
		
		//建筑物使用功能
		List<BuildingFunction> function = buildingFunctionService.queryAllFunction();
		model.addAttribute("function", function);
		
		//维保企业全集
		@SuppressWarnings("rawtypes")
		List<HashMap> enterprise = enterpriseService.queryAllEnterpriseHash();
		model.addAttribute("enterprise", enterprise);
		
		return "contract/addContract";
	}
	
	/**
	 * @author zhyan
	 * @function 编辑合同信息
	 * @date 2018.6.7
	 * @param model
	 * @return
	 * @throws ParseException 
	 * @throws IOException 
	 * @throws IllegalStateException 
	 */
	@RequestMapping("updateContract")
	private String EditContract(MultipartFile file, HttpServletRequest request, Model model) throws ParseException, IllegalStateException, IOException
	{
		int id = Integer.parseInt(request.getParameter("Id"));
		Contract contract = contractService.queryContract(id);
		//SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		
		String projectName = request.getParameter("projectName");
		//String projectNameShort = request.getParameter("projectNameShort");
		int proprietorId = Integer.parseInt(request.getParameter("proprietorId"));
		String province = request.getParameter("province");
		String city = request.getParameter("city");
		String district = request.getParameter("area");
		String address = request.getParameter("address");
		String cityPartner = request.getParameter("cityPartner");
		//int maintenanceEnterpriseId = Integer.parseInt(request.getParameter("maintenanceEnterpriseId"));
		String proprietorProjectContact = request.getParameter("proprietorProjectContact");
		String proprietorSceneContact = request.getParameter("proprietorSceneContact");
		String projectLeaderAccount = userBasicInfoService.getInfoById(Integer.parseInt(request.getParameter("projectCharge"))).getLoginId();
		String singdate=request.getParameter("signDate");
		System.out.println("sign "+singdate);
		Date signDate = sdf.parse(singdate);
		Date endDate = sdf.parse(request.getParameter("endDate"));
		java.sql.Date sqlSignDate = new java.sql.Date(signDate.getTime());
		java.sql.Date sqlEndDate = new java.sql.Date(endDate.getTime());
		BigDecimal totalPrice = new BigDecimal(request.getParameter("totalPrice"));
		String buildingFunction = request.getParameter("buildingFunction");
		String servicePhone = request.getParameter("sevicePhone");
		//String accessory = request.getParameter("accessory");
		String status = request.getParameter("status");
		String accessory = null;
		
		String path = request.getSession().getServletContext().getRealPath("upload");
		String fileName = file.getOriginalFilename();//获取文件名
		
		//只有存在上传文件时，才会执行下面的操作
		if(!fileName.equals(null) && fileName.equals(""))
		{
			File dir = new File(path, fileName);
			
			if (!dir.exists())
			{
				dir.mkdirs();
			}
			// MultipartFile自带的解析方法
			file.transferTo(dir);
			accessory = dir.toString();
		}
		
		contract.setProjectName(projectName);
		//contract.setProjectNameShort(projectNameShort);
		contract.setProprietorId(proprietorId);
		contract.setProvince(province);
		contract.setCity(city);
		contract.setDistrict(district);
		contract.setAddress(address);
		contract.setCityPartner(cityPartner);
		//contract.setMaintenanceEnterpriseId(maintenanceEnterpriseId);
		contract.setProprietorProjectContact(proprietorProjectContact);
		contract.setProprietorSceneContact(proprietorSceneContact);
		contract.setProjectLeaderAccount(projectLeaderAccount);
		contract.setSignDate(sqlSignDate);
		contract.setEndDate(sqlEndDate);
		contract.setTotalPrice(totalPrice);
		contract.setBuildingFunction(buildingFunction);
		contract.setServicePhone(servicePhone);
		contract.setAccessory(accessory);
		contract.setStatus(status);
		
		
		int number = contractService.updateContract(contract);//更新合同信息
		if(number > 0)
		{
			model.addAttribute("message", "true");//更新成功
		}
		else
		{
			model.addAttribute("message", "false");//更新失败
		}
		
		return "redirect:/contract/showContract.htm";
	}
	
     /**
      * @author Liuxc
      * @function 查询维保项目树
      * */
	@RequestMapping("searchMaintenance")
	public String searchMaintenance(HttpServletRequest request,Model model)
	{
		Integer contractId = Integer.parseInt(request.getParameter("Id")) ;//合同ID
		Contract  contract = contractService.queryContract(contractId);//合同
		List<Integer> secondMaintenanceList = new ArrayList<Integer>();//合同中的二级维保目录
		secondMaintenanceList = contractService.selectSecondMaintenance(contractId);
		JSONArray maintenanceTree=new JSONArray();
		List<FirstMaintenanceProject> firstMaintenance = new ArrayList<FirstMaintenanceProject>();
		firstMaintenance = maintenanceService.getAllFirstMaintenance();//查询所有一级目录		
		maintenanceTree = maintenanceService.getMaintenanceTree(firstMaintenance,secondMaintenanceList);//获取维保目录树
		System.out.println(maintenanceTree);
        model.addAttribute("contract", contract);
        model.addAttribute("tree", maintenanceTree);
		return "contract/addProjectTree";
	}
	
	/**
	 * @author Liuxc
	 * 
	 * 更新合同中的维保项目
	 * @throws Exception 
	 * */
	@RequestMapping("checkedId")
	@ResponseBody
	@Transactional
	public String editeMaintenance(HttpServletRequest request,Model model) {
		
		Map<String,Object> map = new HashMap<String,Object>();
		Integer contractId = Integer.parseInt(request.getParameter("contractId")) ;//合同ID
		int buildingNum = buildingService.getNumberOfContract(contractId);
		if(buildingNum == 0){//如果未添加建筑物。不能更新合同维保内容
			map.put("hasBuilding", false);
			return JSONObject.toJSONString(map);
		}
		if(maintenancePlanService.IsContractHasTask(contractId)){
			map.put("canEdite", false);
		}else{
			String[] s =  request.getParameterValues("checkedIdArray");//获取数组使用该函数
		    int[] checkedIdArray = new int[s.length];
		    for (int i = 0; i <s.length; i++){
			    checkedIdArray[i] = Integer.parseInt(s[i]);
		    }
			/**
			 * 自动生成维保计划
			 * */
		    
			Boolean result = maintenancePlanService.creatorPlanUtilAndUpdateMaintenance(contractId,checkedIdArray);

			map.put("flag", result);
		
		}
		return JSONObject.toJSONString(map);
	}
	
	/**
	 * @author zhyan
	 * @function 图片上传功能
	 * @date 2018.6.8
	 * @TIPS 仿网格化代码完成
	 */
/*	@RequestMapping("uploadPicture")
	private String uploadPicture(MultipartFile file, HttpServletRequest request, Model model) throws IllegalStateException, IOException
	{
		int id = Integer.parseInt(request.getParameter("id"));
		String path = request.getSession().getServletContext().getRealPath("upload");
		String fileName = file.getOriginalFilename();//获取文件名
		File dir = new File(path, fileName);
		
		if (!dir.exists())
		{
			dir.mkdirs();
		}
		// MultipartFile自带的解析方法
		file.transferTo(dir);
		
		String accessory = dir.toString();
		Contract record = contractService.queryContract(id);
		record.setAccessory(accessory);;
		int number = contractService.updateContract(record);
		
		if(number > 0)
		{
			model.addAttribute("message", "true");//上传成功，将路径写入数据库
		}
		else
		{
			model.addAttribute("message", "false");//上传失败
		}
		
		return "";
	}*/
	
	/**
	 * @author zhyan
	 * @function 下载图片
	 * @date 2018.6.8
	 * @TIPS：仿网格化项目代码完成
	 */
	@RequestMapping("/down")
	public void down(HttpServletRequest request, HttpServletResponse response) throws Exception{
		int id = Integer.parseInt(request.getParameter("id"));
		Contract record = contractService.queryContract(id);
		
		try
		{
			// 从数据库中获取凭证的完整文件路径
			String filePath = record.getAccessory();
			
			// 获取输入流
			InputStream bis = new BufferedInputStream(new FileInputStream(new File(filePath)));
			// 获取文件名称
			String temp[] = filePath.replaceAll("\\\\", "/").split("/");
			String fileName = "";
			
			if (temp.length > 1)
			{
				fileName = temp[temp.length - 1];
			}
			
			// 设置文件下载头
			response.addHeader("Content-Disposition","attachment;filename=" + fileName);
			// 设置文件ContentType类型，这样设置，会自动判断下载文件类型
			response.setContentType("multipart/form-data");
			BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream());
			int len = 0;
			
			while((len = bis.read()) != -1)
			{
				out.write(len);
				out.flush();
			}
			bis.close();
			out.close();
		}
		catch (Exception e)
		{
			response.sendRedirect(request.getContextPath() + "/Revise/toOrderExport");
		}
	}
	
/*	@Transactional(rollbackFor = Exception.class)
	public void creatorPlanUtil(Integer contractId, int[] checkedIdArray){
		maintenancePlanService.deleteByContractId(contractId);//删除该合同所有计划
//		maintenancePlanService.createYearPlan(contractId,checkedIdArray);//生成年计划
		maintenancePlanService.createMonthPlan(contractId,checkedIdArray);//生成月计划
	}*/
	
}